package com.studynotes.dev.tech.common.pool;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.alibaba.druid.pool.DruidDataSource;
import com.studynotes.dev.tech.common.constant.ConfigConstant;
import com.studynotes.dev.tech.common.utils.JsonUtil;
import com.studynotes.dev.tech.common.utils.SpringContextUtil;
import com.studynotes.dev.tech.model.vo.dataSourceLinkConfig.DataSourceLinkConfigView;
import com.studynotes.dev.tech.service.DataSourceLinkConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Liu XiaoJun
 * @description: 数据源缓存池
 * @date 2025-11-07 15:35:54
 */
public class DataSourceCachePool {

    @Autowired
    private static DataSourceLinkConfigService dataSourceLinkConfigService;

    /** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */
    private static final Map<String, DruidDataSource> dbSources = new HashMap<>();

    private static RedisTemplate<String, Object> redisTemplate;

    private static RedisTemplate<String, Object> getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = SpringContextUtil.getBean("redisTemplate");
        }
        return redisTemplate;
    }

    /**
     * 获取多数据源缓存
     *
     * @param dbLinkKey Spring注入DS的ID
     * @return 数据源链接配置视图对象
     */
    public static DataSourceLinkConfigView getCacheDynamicDataSourceModel(String dbLinkKey) {
        String redisCacheKey = ConfigConstant.SYS_DYNAMIC_DB_CACHE + dbLinkKey;
        if (getRedisTemplate().hasKey(redisCacheKey)) {
            String model = (String)getRedisTemplate().opsForValue().get(redisCacheKey);
            return JsonUtil.parseObject(model,DataSourceLinkConfigView.class);
        }
        DataSourceLinkConfigView dbSource = dataSourceLinkConfigService.get(dbLinkKey);
        if (dbSource != null) {
            getRedisTemplate().opsForValue().set(redisCacheKey, JsonUtil.toJsonString(dbSource));
        }
        return dbSource;
    }

    /**
     * 从本地缓存Map获取数据源配置
     * @param dbLinkKey Spring注入DS的ID
     * @return 数据源配置
     */
    public static DruidDataSource getCacheBasicDataSource(String dbLinkKey) {
        return dbSources.get(dbLinkKey);
    }

    /**
     * put 数据源缓存
     * @param dbLinkKey Spring注入DS的ID
     * @param dataSource 数据源
     */
    public static void putCacheBasicDataSource(String dbLinkKey, DruidDataSource dataSource) {
        dbSources.put(dbLinkKey, dataSource);
    }

    /**
     * 清空数据源缓存
     */
    public static void cleanAllCache() {
        //关闭数据源连接
        for(Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()){
            String dbkey = entry.getKey();
            DruidDataSource druidDataSource = entry.getValue();
            if(druidDataSource!=null && druidDataSource.isEnable()){
                druidDataSource.close();
            }
            //清空redis缓存
            getRedisTemplate().delete(ConfigConstant.SYS_DYNAMICDB_CACHE + dbkey);
        }
        //清空缓存
        dbSources.clear();
    }

    public static void removeCache(String dbKey) {
        //关闭数据源连接
        DruidDataSource druidDataSource = dbSources.get(dbKey);
        if(druidDataSource!=null && druidDataSource.isEnable()){
            druidDataSource.close();
        }
        //清空redis缓存
        getRedisTemplate().delete(ConfigConstant.SYS_DYNAMICDB_CACHE + dbKey);
        //清空缓存
        dbSources.remove(dbKey);
    }

}
